import { UserConfig, ConfigEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import styleImport from 'vite-plugin-style-import'
import { resolve } from 'path'
import { viteMockServe } from 'vite-plugin-mock'
import * as dotenv from 'dotenv'
import * as fs from 'fs'
// import AutoImport from 'unplugin-auto-import/vite'
// import Components from 'unplugin-vue-components/vite'
// import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// import ElementPlus from 'unplugin-element-plus/vite'

const path = (dir: string): string => resolve(__dirname, dir)
const isBuild = false

// https://vitejs.dev/config/
export default ({ command }: ConfigEnv): UserConfig => {
  const NODE_ENV = process.env.NODE_ENV || 'development'
  const envFiles = [
    `.env.${NODE_ENV}`
    
  ]
  for (const file of envFiles) {
    const envConfig = dotenv.parse(fs.readFileSync(file))
    for (const k in envConfig) {
      process.env[k] = envConfig[k]
    }
  }
  return {
    base: '/dist/',
    resolve: {
      alias: [
        {
          find: /^~/,
          replacement: "",
        },
        {
          find: '@',
          replacement: path('./src')
        }
      ]
    },
    define: {
      'process.env': {}
    },
    server: {
      open: true,
      host: 'localhost',
      port: 80,
      proxy: {
        [process.env.VITE_BASE_API]: {
          target: `${process.env.VITE_BASE_PATH}:${process.env.VITE_SERVER_PORT}/`,
          changeOrigin: true,
          rewrite: path => path.replace(new RegExp('^' + process.env.VITE_BASE_API), '')
        }
      }
    },
    preview: {
      open: true,
      host: 'localhost',
      port: 80,
      proxy: {
        [process.env.VITE_BASE_API]: {
          target: `${process.env.VITE_BASE_PATH}:${process.env.VITE_SERVER_PORT}/`,
          changeOrigin: true,
          rewrite: path => path.replace(new RegExp('^' + process.env.VITE_BASE_API), '')
        }
      }
    },
    css: {
      preprocessorOptions: {
        css: { charset: false },
        scss: {
          // 按需引入时，修改自定义主题
          // additionalData: `@use "@/element/index.scss" as *;`,
        },
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          }
        ]
      }
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            'element-plus': ['element-plus'],
          }
        }
      }
    },
    plugins: [
      vue({
        reactivityTransform: true
      }),
      vueJsx(),
      styleImport({
        libs: []
      }),
      viteMockServe({
        ignore: /^\_/,
        mockPath: 'mock',
        localEnabled: !isBuild,
        prodEnabled: isBuild,
        injectCode: `
          import { setupProdMockServer } from '../mock/_createProductionServer';
          setupProdMockServer();
        `,
      }),
      // ElementPlus({
      //   useSource: true,
      // }),
      // 自动引入Element组件
      // AutoImport({
      //   resolvers: [ElementPlusResolver()],
      // }),
      // Components({
      //   resolvers: [
      //     ElementPlusResolver({
      //       importStyle: "sass",
      //     })
      //   ],
      // })
    ]
  }
}
